﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Diagnostics;
using Microsoft.Office.Interop.Excel;

namespace ColdSun.Services
{
    public class ReleaseComObjectService
    {
        [DllImport("user32.dll")]
        static extern uint GetWindowThreadProcessId(IntPtr hWnd, out int ProcessId);

        public static void ReleaseComObject(object releaseComObject)
        {
            if (releaseComObject != null)
            {
                try
                {
                    while (System.Runtime.InteropServices.Marshal.ReleaseComObject(releaseComObject) > 0) ;
                }
                catch { }
                finally
                {
                    releaseComObject = null;
                }
            }
        }

        public static void ReleaseWorkbookObject(Workbook releaseWorkbook)
        {
            ReleaseWorkbookObject(releaseWorkbook, true);
        }

        public static void ReleaseWorkbookObject(Workbook releaseWorkbook, bool isSave)
        {
            if (releaseWorkbook != null)
            {
                if (!isSave)
                {
                    releaseWorkbook.Close(false, Type.Missing, Type.Missing);
                }
                ReleaseComObject(releaseWorkbook);
            }
        }

        public static void ReleaseExcelApplicationObject(Microsoft.Office.Interop.Excel.Application releaseExcelApplication)
        {
            if (releaseExcelApplication != null)
            {
                releaseExcelApplication.Quit();
                int hWnd = releaseExcelApplication.Application.Hwnd;
                int processID;
                GetWindowThreadProcessId((IntPtr)hWnd, out processID);
                Process[] procs = Process.GetProcessesByName("EXCEL");
                foreach (Process p in procs)
                {
                    if (p.Id == processID)
                        p.Kill();
                }
                ReleaseComObject(releaseExcelApplication);
            }
        }
    }
}
